package com.dillon.acr.services.task


import android.app.Service
import android.content.Intent
import android.media.MediaRecorder
import android.os.Handler
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.dillon.acr.base.App
import com.dillon.acr.key.CacheK
import com.dillon.acr.key.CommonK
import com.dillon.acr.receivers.CallRec
import com.dillon.acr.utils.AUtils
import com.dillon.acr.utils.LocalCacheUtils.saveProExp
import java.io.File
import java.text.SimpleDateFormat
import java.util.*


class RecorderSer : TempService() {
    private var aRec: CallRec? = null

    private var mMediaRecorder: MediaRecorder? = null
    private var mFile: File? = null
    private var maxDur = 5 * 60 * 60 * 1000 //5小时
    override fun onCreate() {
        super.onCreate()
        AUtils.makeNotification(this, CommonK.CHANNEL_ID, CommonK.CHANNEL_NAME)
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val acrOpen = SPUtils.getInstance().getBoolean(CacheK.acOpen, true)
        if (acrOpen) {
            if (App.capturingAudio) {
                startRecord(App.number)
            } else {
                stopRecord()
            }
        }
        return Service.START_STICKY
    }


    private fun startRecord(number: String) {
        Handler().postDelayed({
            val time = SimpleDateFormat("yyyyMMddhhmmss").format(Date())
            if (mMediaRecorder == null) mMediaRecorder = MediaRecorder()
            mFile = File(App.saveAudioDir, number + "_" + time + ".m4a")
            try {
                mMediaRecorder?.setAudioSource(MediaRecorder.AudioSource.VOICE_RECOGNITION)
                mMediaRecorder?.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
                mMediaRecorder?.setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
                mMediaRecorder?.setOutputFile(mFile?.absolutePath)
                mMediaRecorder?.setMaxDuration(maxDur)
                mMediaRecorder?.prepare()
                mMediaRecorder?.start()
                LogUtils.v("startRecord|$number")
            } catch (e: Exception) {
                //
            }
        }, 500)

    }

    private fun stopRecord() {
        App.capturingAudio = false
        try {
            if (mMediaRecorder != null) {
                saveProExp(1)
                LogUtils.v("stopRecord", mFile)
                mMediaRecorder?.stop()
                mMediaRecorder?.reset()
                mMediaRecorder?.release()
                mMediaRecorder = null
                mFile = null
            }

        } catch (e: Exception) {
            //  e.printStackTrace()
        }
    }

}